// const baseUrl = 'http://localhost:1890/'; //本地
// const baseUrl = 'http://175.178.156.135:1890/'; //测试站
const baseUrl = 'https://bottle.jiaoguanyi.com/';
const config = {
	// 请求拦截器
	beforeRequest(options = {}) {
		return new Promise((resolve, reject) => {
			options.url = options.url
			options.method = options.method || 'GET';
			options.data = options.data;
			options.header = options.header
			resolve(options)
		})
	},
	// 响应拦截器
	handleResponse(result) {
		return new Promise((resolve, reject) => {
			if (result.data.code != 200) {
				reject(result.data)
			}else {
				const {
					data
				} = result;
				const dataHandler = data;
				resolve(dataHandler)
			}
		})
	}
}


const request = (method, url, data, header = {}) => {
	header = {
		'Content-type': 'application/json',
		'x-token': uni.getStorageSync('token')
	}
	let options = {
		method: method,
		url: baseUrl + url,
		data: data,
		dataType: 'json',
		header: header
	}

	return config.beforeRequest(options).then(opt => {

		return new Promise((resolve, reject) => {
			uni.request(Object.assign(opt, {
				success: (res) => {
					resolve(res)
				},
				fail: (err) => {
					reject(err)
				}
			}))
		})
	}).then(res => {
		return config.handleResponse(res)
	})
}

export default function(method = 'get', url = '', data = {}) {
	method = method.toLowerCase();
	if (method == 'post') {
		return request('post', url, data)
	} else if (method == 'get') {
		return request('get', url, data)
	} else if (method == 'delete') {
		return request('delete', url, {
			params: data
		})
	} else if (method == 'put') {
		return request('put', url, data)
	} else {
		console.error('未知的method' + method)
		return false
	}
}

/**
 * @description: 将小程序api封装成Promise
 * @param {any} func js api，例如tt.login
 * @param {*} options 传入api的参数
 * @return {*}
 */
export function promisify(func, options = {}) {
	return new Promise((resolve, reject) => {
		func({
			...options,
			success(res) {
				resolve(res);
			},
			fail(err) {
				reject(err);
			},
		});
	});
}